package com.yunsom.testdemo.util;


import java.io.*;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName ConvertUtil
 * @Description 拷贝工具类
 * @Author cxb
 * @Date 2023-3-27 10:59
 * @Version 1.0.0
 */
public class CopyUtil {

    public static<T> List<T> deepCopy(List<T> sourceList) {
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
        List<T> result = null;
        try {
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            out = new ObjectOutputStream(byteOut);
            out.writeObject(sourceList);

            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            in = new ObjectInputStream(byteIn);

            result = (List<T>) in.readObject();

        }catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (Objects.nonNull(out)){
                    out.close();
                }
                if (Objects.nonNull(in)){
                    in.close();
                }
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
